<script lang="ts" setup>
import { useMenuStore } from "@/stores/menu.ts"
import type { MenuStructure } from "@/api/menu.ts"

const store = useMenuStore()
const { menus } = toRefs(store.state)
const { proxy } = getCurrentInstance()!
watchEffect(() => {
  store.getMenuList()
})

const editType = ref(-1)
const editData = ref<MenuStructure | undefined>(undefined)
const setting = ref(false)
const panelTitle = computed(() =>
  editType.value === 0 ? "添加角色" : "编辑角色"
)

const handleAddMenu = () => {
  editType.value = 0
  setting.value = true
  editData.value = {} as MenuStructure
}

const handleEditMenu = (menu: MenuStructure) => {
  editType.value = 1
  setting.value = true
  editData.value = { ...menu }
}

const handleDeleteMenu = async (menu: MenuStructure) => {
  try {
    await proxy?.$confirm("此操作将永久删除该菜单, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    await store.deleteMenu(menu.id)
    proxy?.$message.success("删除成功")
  } catch {
    proxy?.$message.info("取消")
  }
}

const addMenu = async (menu: MenuStructure) => {
  await store.addMenu(menu)
  proxy?.$message.success("添加成功")
  setting.value = false
}

const editMenu = async (menu: MenuStructure) => {
  await store.updateMenu(menu)
  proxy?.$message.success("编辑成功")
  setting.value = false
}

const handleSubmit = async (editData: MenuStructure) => {
  if (editType.value === 0) {
    await addMenu(editData)
  } else {
    await editMenu(editData)
  }
}
</script>

<template>
  <div p-30px>
    <h2>菜单管理</h2>
    <el-button @click="handleAddMenu">菜单添加</el-button>
    <el-table
      :data="menus"
      border
      default-expand-all
      row-key="id"
      style="width: 100%; margin-bottom: 20px"
    >
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="名称" prop="name"></el-table-column>
      <el-table-column label="icon" prop="icon"></el-table-column>
      <el-table-column label="url" prop="url"></el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleEditMenu(scope.row)"
            >编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDeleteMenu(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <right-panel v-model="setting" :title="panelTitle">
      <editor-menu
        :data="editData"
        :type="editType"
        @submit="handleSubmit"
      ></editor-menu>
    </right-panel>
  </div>
</template>

<style scoped></style>
